package no.la58.scribbles.client;

import java.util.logging.Logger;

import no.la58.scribbles.client.event.LoggedInEvent;
import no.la58.scribbles.client.event.ScribblesUpdateEvent;
import no.la58.scribbles.client.uicomponents.LoginView;
import no.la58.scribbles.client.uicomponents.MainPage;
import no.la58.scribbles.shared.GetScribbleRequest;
import no.la58.scribbles.shared.LoggedInResponse;
import no.la58.scribbles.shared.ScribbleList;
import no.la58.scribbles.shared.UserLocation;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Scribbles implements EntryPoint {

    private static ClientFactory clientFactory = GWT.create(ClientFactory.class);
    private static Logger log = Logger.getLogger(Scribbles.class.getName());

    public void onModuleLoad() {
	checkLogin();
	RootPanel.get("contentM").add(new MainPage());
	RootPanel.get("loginField").add(new LoginView());
	startMessageListener();
    }

    private void startMessageListener() {
	final GetScribbleRequest request = new GetScribbleRequest();
	final AsyncCallback<ScribbleList> callback = new AsyncCallback<ScribbleList>() {

	    @Override
	    public void onSuccess(ScribbleList result) {
		if (result.hasNewScribbles()) {
		    ScribblesUpdateEvent event = new ScribblesUpdateEvent();
		    event.setScribbles(result);
		    clientFactory.getEventBus().fireEvent(event);
		    request.setMaximumAge(System.currentTimeMillis());
		}
	    }

	    @Override
	    public void onFailure(Throwable caught) {
		log.severe("Could not get messages: " + caught.getMessage());
	    }
	};
	Timer t = new Timer() {
	    @Override
	    public void run() {
		clientFactory.getMessageService().getScribbles(request, callback);
	    }
	};
	t.schedule(100);
	t.scheduleRepeating(5000);
    }

    private void checkLogin() {
	UserLocation location = new UserLocation();
	location.setCallersUrl(Window.Location.getHref());
	AsyncCallback<LoggedInResponse> callback = new AsyncCallback<LoggedInResponse>() {

	    @Override
	    public void onSuccess(LoggedInResponse result) {
		LoggedInEvent loggedInEvent = new LoggedInEvent(result);
		clientFactory.getEventBus().fireEvent(loggedInEvent);
	    }

	    @Override
	    public void onFailure(Throwable caught) {
		log.severe("Userservice failed to check login " + caught.getMessage());

	    }
	};
	clientFactory.getSecurityService().isLoggedIn(location, callback);
    }
}
